from datetime import datetime

from dbs import Dao

class SecureDao(Dao):
    def __init__(self):
        super(SecureDao, self).__init__()
        self.table = 'tb_user_secure'

    def check_fields(self, *fields, **item):
        # 检查fields所有的字段是否全在item的keys()中
        fs = set(fields)
        ks = set(item.keys())
        return fs & ks == fs

    def add(self, **item):
        if self.check_fields('title','result','uid', **item):
            item.setdefault('update_date', datetime.now().strftime('%Y-%m-%d'))
            return self.save(self.table, **item)

        raise Exception('数据库的字段不完整')

    def list(self, user_id):
        return self.query(self.table, 'title', 'result', 'update_date', 'id', where='uid=%s', args=(user_id,))

    def update(self, **data):
        # data = locals()  # 将局部变量转成字典的key:value结构
        # data.pop('self') # 将多余self对象删除
        # data.pop('__class__')
        #
        # data['id'] = data.pop('secure_id') # 密保问题的ID
        # data['uid'] = data.pop('user_id')
        data.setdefault('update_date', datetime.now().strftime('%Y-%m-%d'))
        # update xxx set title='',result='' where id=1 and user_id=1
        return super().update(self.table, pk='id', extra_where_field='uid', **data)

    def delete(self, **where):
        if not self.check_fields('id', 'uid', **where):
            raise Exception('条件中必须存在id和uid')

        # where -> id=1, uid=3
        # ' id=%(id)s and uid=%(uid)s'
        where_sql = ' and '.join([f'{k}=%({k})s' for k in where])
        return super(SecureDao, self).delete(self.table, where_sql, args=where)

